package com.sqx.modules.health.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sqx.modules.health.common.ApiConsts;
import com.sqx.modules.health.entity.*;
import com.sqx.modules.health.mapper.ReceiveMapper;
import com.sqx.modules.health.service.*;
import com.sqx.modules.health.vo.SrcDataValue;
import com.sqx.modules.sys.entity.SysUserEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;


/***************************************************************************
 *  @Description     : 血压设备数据采集service
 *
 *  @Author          : gxy
 ***************************************************************************/
@Slf4j
@Service
public class ReceivePressureDataServiceImpl implements ReceivePressureDataService {

    private static Logger logger = LoggerFactory.getLogger(ReceivePressureDataServiceImpl.class);
    @Autowired
    private IReceiveService receiveService;
    @Autowired
    private ReceiveMapper receiveMapper;
    @Autowired
    private INcgDeviceWatchService deviceWatchService;
    @Autowired
    private IWarningService warningService;
    @Autowired
    private IRecordService recordService;
    @Autowired
    private IRecordsetService recordsetService;
    @Autowired
    private INcgDeviceWatchService watchService;
    @Autowired
    private ISurveyrecordService surveyrecordService;

    @Autowired
    private IUserService userService;

    /**
     * 处理上报的数据
     *
     * @param srcDatavalue
     * @return
     */
    @Override
    public boolean handleReceivedData(SrcDataValue srcDatavalue) {
        //血压
        String patientId = UUID.randomUUID().toString();
        String devSN = srcDatavalue.getSerialNumber();
        boolean flag = true;

        Integer userId = null;
        Integer doctorid= null;

        NcgDeviceWatch transferDeviceWatch =  watchService.getOne(new QueryWrapper<NcgDeviceWatch>()
                .eq(ObjectUtil.isNotEmpty(devSN),"imei", devSN));
        if (null == transferDeviceWatch) {
            flag = false;
            return flag;
        }

        if (StringUtils.isEmpty(transferDeviceWatch.getTransferuid())) {
            userId = Math.toIntExact(transferDeviceWatch.getUid());
            SysUserEntity user = userService.getById(userId);
            if (ObjectUtil.isNotEmpty(user)) {
                doctorid = Math.toIntExact(user.getBelongsDoctor());
            }
           /* userId = Integer.parseInt(srcDatavalue.getCustomer());
            if (StringUtils.isEmpty(srcDatavalue.getUser())) {
                doctorid = Integer.parseInt(srcDatavalue.getUser());
            }*/
        } else {
            SysUserEntity transferUser = userService.findByUid(transferDeviceWatch.getTransferuid());
            if (ObjectUtil.isNotEmpty(transferUser)) {
                userId = Math.toIntExact(transferUser.getUserId());
                if (transferUser.getBelongsDoctor() != null && transferUser.getBelongsDoctor() != 0) {
                    doctorid = Math.toIntExact(transferUser.getBelongsDoctor());
                }
                transferDeviceWatch.setTransferuid("");
                watchService.updateById(transferDeviceWatch);
            }
        }

        try {
            Receive receive = new Receive();
            receive.setPatientId(patientId);
            receive.setUid(userId);
            receive.setDoctorid(doctorid);
            String createTime = "20" + srcDatavalue.getYear() + "-" + srcDatavalue.getMonth() + "-" + srcDatavalue.getDay();
            createTime = createTime + " " + srcDatavalue.getHour() + ":" + srcDatavalue.getMinute() + ":00";
            receive.setCreatetime(createTime);
            receive.setVersion(srcDatavalue.getVersion());
            receive.setImei(srcDatavalue.getImsi());
            receive.setDeviceType(srcDatavalue.getDeviceType());
            receive.setDevSN(devSN);
            receive.setSys(srcDatavalue.getData1());
            receive.setDia(srcDatavalue.getData2());
            receive.setPul(srcDatavalue.getData3());
            checkWarning(receive);
            boolean result = receiveService.save(receive);
            if (!result) {
                flag = false;
            }

            String dpreStr = ApiConsts.DataTypeEnum.BLPRESSURE.getDPre();
            boolean status = dpreStr.contains(devSN);
            if(status) {
                System.out.println("包含");
                Record record = recordService.getOneByDevSn(devSN, 3);
                if (ObjectUtil.isNotEmpty(record)) {
                    Surveyrecord surveyrecord = new Surveyrecord();
                    surveyrecord.setPatid(record.getPatid());
                    surveyrecord.setShrink(Integer.parseInt(srcDatavalue.getData1()));
                    surveyrecord.setDiastole(Integer.parseInt(srcDatavalue.getData2()));
                    surveyrecord.setPulse(Integer.parseInt(srcDatavalue.getData3()));
                    surveyrecord.setRate(Integer.parseInt(srcDatavalue.getData3()));
                    surveyrecord.setSampleDate(LocalDateTime.parse(createTime,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    surveyrecordService.save(surveyrecord);
                }
            }else {

                QueryWrapper<NcgDeviceWatch> wwwrapper = new QueryWrapper<NcgDeviceWatch>()
                        .eq(ObjectUtil.isNotEmpty(devSN),"imei", devSN);
                NcgDeviceWatch deviceWatch =  watchService.getOne(wwwrapper);

                if (deviceWatch.getPositionid() == 1){

                    System.out.println("不包含");
                    Record record = recordService.getOneByDevSn(devSN, 2);
                    if (ObjectUtil.isNotEmpty(record)) {
//                        if (!ObjectUtil.equals(record.getFlag(), 0)) {
//                            logger.info("创建时间",createTime);
//                            record.setId(null);
//                            record.setRecordtime(createTime);
//                        }
                        record.setRecordtime(createTime);
                        record.setSys(Integer.parseInt(srcDatavalue.getData1()));
                        record.setDia(Integer.parseInt(srcDatavalue.getData2()));
                        record.setPul(Integer.parseInt(srcDatavalue.getData3()));
                        record.setFlag(1);
                        recordService.saveOrUpdate(record);

                        Recordset recordset = recordsetService.getLast(devSN);
                        recordset.setStatus(1);
                        recordset.setEnddate(LocalDateTime.now());
                        recordsetService.saveOrUpdate(recordset);

                        LambdaUpdateWrapper<NcgDeviceWatch> wrapper = new LambdaUpdateWrapper<NcgDeviceWatch>()
                                .set(NcgDeviceWatch::getDoctorid, null)
                                .set(NcgDeviceWatch::getUid, null)
                                .set(NcgDeviceWatch::getStatus, 3)
                                .eq(ObjectUtil.isNotEmpty(devSN), NcgDeviceWatch::getImei, devSN);
                        watchService.update(wrapper);

                    }
                }else {

                    Record records = new Record();
                    /*records.setUid(deviceWatch.getUid());
                    records.setDoctorid(deviceWatch.getDoctorid());*/
                    records.setUid((long) userId);

                    if (doctorid != null) {
                        records.setDoctorid((long) doctorid);
                    }

                    records.setImei(devSN);
                    records.setType(2);
                    records.setRecordtime(createTime);
                    records.setSys(Integer.parseInt(srcDatavalue.getData1()));
                    records.setDia(Integer.parseInt(srcDatavalue.getData2()));
                    records.setPul(Integer.parseInt(srcDatavalue.getData3()));
                    records.setFlag(1);

                    recordService.save(records);

                    Recordset recordset = new Recordset();
                    recordset.setImei(devSN);
                    recordset.setStartdate(LocalDateTime.now());
                    recordset.setEnddate(LocalDateTime.now());
                    /*recordset.setUid(deviceWatch.getUid());
                    recordset.setDocid(deviceWatch.getDoctorid());*/

                    recordset.setUid((long) userId);

                    if (doctorid != null) {
                        recordset.setDocid((long) doctorid);
                    }

                    recordset.setStatus(1);
                    recordset.setDevicetype(2);
                    recordsetService.save(recordset);

                }
            }

        } catch (Exception e) {
            logger.error("GPRS血压设备血压上传异常", e);

        }
        return flag;
    }

    /**
     * 验证血压和脉搏是否处于健康范围
     *
     * @param receive
     */
    private void checkWarning(Receive receive) {
        Warning warning = new Warning();
        StringBuilder waringMessage = new StringBuilder();
        /**
         *  舒张压 收缩压
         *  1级高血压:属于轻度高血压收缩压> 140或舒张压> 90
         *  2级高血压:中度高血压收缩压> 160或舒张压> 100
         *  3级高血压:属于重度高血压，收缩压或舒张压> 110 > 180
         */
        if (receive.getSys() != null && receive.getDia() != null) {
            if (Integer.parseInt(receive.getSys()) > 140 && Integer.parseInt(receive.getDia()) > 90) {
                waringMessage.append("一级高血压").append(",");
                warning.setSys(String.valueOf(receive.getSys()));
                warning.setDia(String.valueOf(receive.getDia()));
                saveData(receive, warning, waringMessage);
            } else if (Integer.parseInt(receive.getSys()) > 160 && Integer.parseInt(receive.getDia()) > 100) {
                waringMessage.append("二级高血压").append(",");
                warning.setSys(String.valueOf(receive.getSys()));
                warning.setDia(String.valueOf(receive.getDia()));
                saveData(receive, warning, waringMessage);
            } else if (Integer.parseInt(receive.getSys()) > 180 && Integer.parseInt(receive.getDia()) > 110) {
                waringMessage.append("三级高血压").append(",");
                warning.setSys(String.valueOf(receive.getSys()));
                warning.setDia(String.valueOf(receive.getDia()));
                saveData(receive, warning, waringMessage);
            } else {
                return;
            }
        }

        /**
         * 脉搏
         * 脉搏的正常范围是60-100次/min之间，它对应的是心率，正常心率范围也是此值，是成人正常值范围。
         * 如果脉率大于100次/min就称为心动过速
         * 如果脉率小于60次/min就称为心动过缓
         */
        if (receive.getPul() != null) {
            if (Integer.parseInt(receive.getPul()) > 100) {
                waringMessage.append("心动过速").append(",");
                saveData(receive, warning, waringMessage);
            } else if (Integer.parseInt(receive.getPul()) < 60) {
                waringMessage.append("心动过缓");
                saveData(receive, warning, waringMessage);
            }
        }
    }

    private void saveData(Receive receive, Warning warning, StringBuilder waringMessage) {
        // 根据 IMEI 获取绑定的用户
        QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<>();
        wrapper.eq("imei", receive.getImei());
        NcgDeviceWatch one = deviceWatchService.getOne(wrapper);
        warning.setId(UUID.randomUUID().toString().replace("-", ""));
        //具有转换功能的对象
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // String 转为 LocalDateTime
        LocalDateTime parse = LocalDateTime.parse(receive.getCreatetime(), df);
        warning.setCreatetime(parse);
        warning.setImei(receive.getImei());
        warning.setDevSN(receive.getDevSN());
        warning.setUid(one != null ? one.getUid() : null);
        warning.setWarningType(waringMessage.toString());
        warning.setSource("爱奥乐血压计");
        warningService.save(warning);
    }

}
